//
//  StatusDAL.swift
//  weibobbaj
//
//  Created by Tiffany宝 on 16/5/4.
//  Copyright © 2016年 Tiffany. All rights reserved.
//首页新浪微博数据的访问层,这一层封装了从数据库里面请求数据和从网络请求数据

import UIKit

let MaxCacheTimeInterval: NSTimeInterval = 60 * 60 * 24 * 7

class StatusDAL: NSObject {
    
    //加载数据的方法 (成功加载,把字典数组回调)
    class func loadData(max_id: Int64,since_id: Int64,completed:(dicts:[[String : AnyObject]]?) -> ()) {
    
        //1.判断本地是否有数据
        if  let result = self.checkCacheData(max_id, since_id: since_id) where result.count > 0{
            //代表本地有
            //2.如果有,则从本地数据库中加载数据,不需要再通过网络请求数据
            completed(dicts: result)
            return
        }
    
        //3.如果没有,则从网络中请求数据
        let url = "https://api.weibo.com/2/statuses/home_timeline.json"
        
        guard let account = UserAccountViewModel.sharedViewModel.account?.access_token else{
            
            return
        }
        
        let parameters = [
            "access_token":account,
            "max_id":"\(max_id)",
            "since_id":"\(since_id)"]
        //        let parameters = ["access_token":account,"max_id":max_id]
        
        NetworkTools.sharedTools.request( urlString: url, parameters: parameters) { (responseObject, error) -> Void in
            
            if error != nil{
                
                print(error)
//                finished(isSuccess: false,count: 0)
                completed(dicts: nil)
                return
            }
            
            //打印请求的微博数据
            //            print(responseObject)
            
            guard let dic = responseObject as? [String : AnyObject] else{
                
                print("字典格式错误")
//                finished(isSuccess: false,count: 0)
                completed(dicts: nil)
                return
            }
            
            guard let arr = dic["statuses"] as? [[String : AnyObject]] else{
                
//                finished(isSuccess: false,count: 0)
                completed(dicts: nil)
                return
            }
            
        //4.数据请求回来之后保存到本地数据库(已完成)
            StatusDAL.cacheData(arr)
            
        //5.回调数据(网络请求数据为异步传输)
            completed(dicts: arr)
        }
    }
    
    /**
     清除缓存
     */
    class func clearCache() {
        
        //计算出距离当前时间七天前的时间
        let targetDate = NSDate(timeIntervalSinceNow: -MaxCacheTimeInterval)
        
        let fm = NSDateFormatter()
        fm.locale = NSLocale(localeIdentifier: "en")
        fm.dateFormat = "yyyy-MM-dd HH:mm:ss"
        
        let targetDataString = fm.stringFromDate(targetDate)
        
        //sql语句
        let sql = "DELETE FROM T_Status WHERE datetime < '\(targetDataString)'"
        
        //执行语句
        SQLiteManager.sharedManager.queue.inDatabase { (db) -> Void in
            
            if db.executeUpdate(sql, withArgumentsInArray: nil){
                print("删除成功")
            }else{
                print("删除失败")
            }
        }
    }
    
    /**
     检查本地是否有数据
     这个方法的返回值:微博字典的数组
     */
    class func checkCacheData(max_id: Int64,since_id: Int64) -> [[String: AnyObject]]? {
        
        guard let uid = UserAccountViewModel.sharedViewModel.account?.uid else{
            return nil
        }
        
        //定义sql语句
        var sql = "SELECT statusid,status,uid FROM T_Status \n"
        
        //添加条件
        if max_id > 0{
            sql += "WHERE statusid <= \(max_id) \n"
        }else{
            sql += "WHERE statusid > \(since_id) \n"
        }
        
        //uid (避免别人登录你应用,然后显示的本地数据库是你之前浏览的内容
        sql += "AND uid = \(uid) \n"
        
        //微博顺序
        sql += "ORDER BY statusid DESC \n"
        
        //最多条数
        sql += "LIMIT 20"
        
        //执行sql语句 (返回符合 sql 语句条件的所有数据)
        let rs = SQLiteManager.sharedManager.execRecordSet(sql)
        
        var result = [[String: AnyObject]]()
        //将数据进行反序列化 (value 为每一条数据~即字典)
        for value in rs{
            
            let dic = try! NSJSONSerialization.JSONObjectWithData(value["status"] as! NSData, options: []) as! [String : AnyObject]
            result.append(dic)
        }
        return result
    }
     
    
    /**
    *  保存从网络上请求回来的数据到数据库(上面的第4步)
    */
    class func cacheData(datas: [[String: AnyObject]]){
        
        guard let uid = UserAccountViewModel.sharedViewModel.account?.uid else{
            return
        }
        
        //1.定义sql语句 (? 为占位符)
        let sql = "INSERT INTO T_Status (statusid,status,uid) VALUES (?,?,?)"
        
        //2.执行sql语句 (网络上请求的数据为多条,则用 inTransaction ~ 若只为 1 条,则用 inDatabase )
        SQLiteManager.sharedManager.queue.inTransaction { (db, rollback) -> Void in
        
            // 一个value 代表一条微博的数据(字典)
            for value in datas{
             
            let statusid = value["id"]!
            let status = try! NSJSONSerialization.dataWithJSONObject(value, options: [])
            
                if db.executeUpdate(sql, withArgumentsInArray: [statusid,status,uid]){
                    print("保存成功")
                }else{
                    print("保存失败")
                    //一旦保存失败,即刻回滚
                    rollback.memory = true
                }
            }
        }
    }
}
